package it.java.giw.dataextraction.aleph.wrapper.bestmovie;

import it.java.giw.dataextraction.aleph.helper.CSVHelper;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlPage;

public class BestMovieWrapperWorker implements Runnable {

	private LinkedBlockingQueue<String> datasetFiles;
	private final CountDownLatch startSignal;
	private final CountDownLatch doneSignal;
	private HashMap<String, String> attr2xpath;

	private List<String[]> results;
	private CSVHelper helper;

	/*EXAMPLES
    System.out.println(page.getTitleText());
    System.out.println(page.getHtmlElementById("footer"));
    //System.out.println(page.getAnchorByName("anchor_name"));

    //get list of all divs
    System.out.println(page.getByXPath("//div"));
    final String pageAsXml = page.asXml();
    System.out.println(pageAsXml.contains("<body class=\"composite\">"));
    final String pageAsText = page.asText();
    System.out.println(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
	 */

	public BestMovieWrapperWorker(LinkedBlockingQueue<String> datasetFiles, CountDownLatch startSignal, CountDownLatch doneSignal, CSVHelper helper) {
		this.datasetFiles = datasetFiles;
		this.startSignal = startSignal;
		this.doneSignal = doneSignal;
		this.results = new ArrayList<String[]>();
		this.attr2xpath = new HashMap<String,String>();
		this.helper = helper;
		initMap();
	}

	private void initMap() {
		/* xpaths di bestmovies */
		attr2xpath = new HashMap<String, String>();
		attr2xpath.put("title", "//div[@id='NOTIZIA_DETTAGLIO']/div/h1/text()");
		attr2xpath.put("directors", "//*[text()[contains(.,'Regia:')]]/../td[2]/text()");
		attr2xpath.put("genre", "//*[text()[contains(.,'Genere:')]]/../td[2]/text()");
		attr2xpath.put("year", "string(//*[text()[contains(.,'Anno:')]]/../td[2]/text())");
		attr2xpath.put("rating", "string(//*[@id='VOTA_FILM']//strong/text())");
		attr2xpath.put("actor1", "concat(string(//*[text()[contains(.,'Interpreti:')]]/../td[2]/p/text()), string(//*[text()[contains(.,'Interpreti:')]]/../td[2]/text()),string(//*[text()[contains(.,'Interpreti:')]]/../td[2]/div/text()))");
		attr2xpath.put("poster", "string(//*[@id='SCHEDA_FILM']/img/@src)");
		attr2xpath.put("trailer", "string(//*[@id='VIDEO_TRAILER']//@src)");

		/* fine xpaths bestmovies */

	}

	public void run() {
		try {
			startSignal.await();
			while(!datasetFiles.isEmpty()){
				/* create webClient and set options to get only HTML */
				final WebClient webClient = new WebClient();
				//		webClient.getOptions().setThrowExceptionOnScriptError(false);
				webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
				webClient.getOptions().setCssEnabled(false);
				webClient.getOptions().setJavaScriptEnabled(false);
				webClient.getOptions().setAppletEnabled(false);

				//			    final HtmlPage page = webClient.getPage("file:///C:/Users/Roberto/Dropbox/Università-Roma3/Workspace Eclipse/AlephDataExtractor/downloads/00000.html");
				//			    final HtmlPage page = webClient.getPage("file:///download/"+id+".html");
				HtmlPage page;
				try {
					String[] info = new String[10];
					String filename = datasetFiles.poll();
					page = webClient.getPage("file:///C:/Users/Francesco/Desktop/Nuova cartella/AlephDataExtractor/download/"+filename);
					//				    System.out.println(page.getByXPath("//h1[1]/text()"));
					info[0] = filename;
					//title
					info[1] = page.getByXPath(attr2xpath.get("title")).get(0).toString();
					//director(s)
					info[2] = "";
					for (Object director : page.getByXPath(attr2xpath.get("directors")))
							info[2] += director.toString()+";";
//					System.out.println(info[1]);
					info[3]= page.getByXPath(attr2xpath.get("genre")).get(0).toString();
					info[4]= page.getByXPath(attr2xpath.get("year")).get(0).toString();
					info[5]= page.getByXPath(attr2xpath.get("rating")).get(0).toString();
					info[6]= page.getByXPath(attr2xpath.get("actor1")).get(0).toString();
					info[7]= page.getByXPath(attr2xpath.get("poster")).get(0).toString();
					info[8]= page.getByXPath(attr2xpath.get("trailer")).get(0).toString();

					
					results.add(info);

				} catch (FailingHttpStatusCodeException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		} catch (InterruptedException e1) {
			e1.printStackTrace();
			doneSignal.countDown();
		}finally{
			try {
				for(String[] row : results)
					helper.writeCSV(row,"Collection BestMovie.csv");
			} catch (Exception e) {
				e.printStackTrace();
			}
			doneSignal.countDown();
		}
	}
}
